﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Aspose.Words;
using Aspose.Cells;
//using Aspose.Slides;
using KingRoad.EPM.Web.Areas.CompletionMaterials.ViewModels;
using ElFinder;
using KingRoad.EPM.CompletionMaterialsEntity.Model;

namespace KingRoad.EPM.Web.Areas.CompletionMaterials.Controllers
{
    public class FileManagerController : BaseController
    {
        public ActionResult Index(string filePath)
        {
            if (String.IsNullOrEmpty(filePath)) return View();

       

            var index = filePath.IndexOf('/');

            var objfolderName = filePath.Substring(0, index);


            var pkId = filePath.Substring(filePath.LastIndexOf('/') + 1);
            var subFolder = filePath.Substring(index + 1);


            string filePhysicalPath = Server.MapPath(String.Format("~/Files/{0}", filePath));
            if (!Directory.Exists(filePhysicalPath))//判断上传文件夹是否存在，若不存在，则创建
            {
                Directory.CreateDirectory(filePhysicalPath);//创建文件夹
            }

            FileViewModel model = new FileViewModel() { Folder = objfolderName, SubFolder = subFolder, PkId = pkId };

            return View(model);
        }


        public virtual ActionResult FileMgr(string folder, string subFolder)
        {
            FileSystemDriver driver = new FileSystemDriver();

            var root = new Root(
                new DirectoryInfo(Server.MapPath("~/Files/" + folder)),
                "http://" + Request.Url.Authority + "/Files/" + folder)
            {
                // Sample using ASP.NET built in Membership functionality...
                // Only the super user can READ (download files) & WRITE (create folders/files/upload files).
                // Other users can only READ (download files)
                // IsReadOnly = !User.IsInRole(AccountController.SuperUser)

                IsReadOnly = false, // Can be readonly according to user's membership permission
                Alias = "Files", // Beautiful name given to the root/home folder
                MaxUploadSizeInKb = 102400, // Limit imposed to user uploaded file <= 102400 KB
                LockedFolders = new List<string>(new string[] { "Folder1" }),

            };

            // Was a subfolder selected in Home Index page?
            if (!string.IsNullOrEmpty(subFolder))
            {
                root.StartPath = new DirectoryInfo(Server.MapPath("~/Files/" + folder + "/" + subFolder));
            }

            driver.AddRoot(root);

            var connector = new ElFinder.Connector(driver);

            return connector.Process(this.HttpContext.Request);
        }

        public virtual ActionResult SelectFile(string target)
        {
            FileSystemDriver driver = new FileSystemDriver();

            driver.AddRoot(
                new Root(
                        new DirectoryInfo(Server.MapPath("~/Files")),
                        "http://" + Request.Url.Authority + "/Files")
                { IsReadOnly = false });

            var connector = new ElFinder.Connector(driver);

            return Json(connector.GetFileByHash(target).FullName);
        }

        public ActionResult InsertFileToDB(string pkId, List<string> fileStr)
        {
            var listFile = new List<ScmAttachsfilesInfo>();

            fileStr.ForEach(t =>
            {

                var inforArray = t.Split(new[] { '$' }, StringSplitOptions.RemoveEmptyEntries);

                listFile.Add(new ScmAttachsfilesInfo
                {
                    Af_ID = Guid.NewGuid().ToString(),
                    Af_PrimayID = pkId,
                    Af_AttachFormat = inforArray[2],
                    Af_AttachName = inforArray[0],
                    Af_AttachSize = Convert.ToDecimal(inforArray[1]),
                });
            });
            ScmAttachsfilesUIRule.InsertObjs(listFile);
            return null;
        }

        public ActionResult ScanFile(string filePath)
        {
            var index = filePath.IndexOf('/');

            var objfolderName = filePath.Substring(0, index);


            var pkId = filePath.Substring(filePath.LastIndexOf('/') + 1);
            var subFolder = filePath.Substring(index + 1);


            string filePhysicalPath = Server.MapPath(String.Format("~/Files/{0}", filePath));
            if (!Directory.Exists(filePhysicalPath))//判断上传文件夹是否存在，若不存在，则创建
            {
                Directory.CreateDirectory(filePhysicalPath);//创建文件夹
            }

            FileViewModel model = new FileViewModel() { Folder = objfolderName, SubFolder = subFolder, PkId = pkId };

            return View(model);
        }

        public ActionResult SaveScanFilesToServer(string filePath)
        {
            try
            {
                String strImageName;
                var files = HttpContext.Request.Files;//   HttpContext.Current.Request.Files;
                var uploadfile = files["RemoteFile"];
                strImageName = uploadfile.FileName;


                uploadfile.SaveAs(filePath + "\\" + strImageName);

                //uploadfile.SaveAs(Server.MapPath(".") + "\\UploadedImages\\" + strImageName);
            }
            catch
            {
            }
            return null;
        }

        public ActionResult ConverFileToPdf(string filePath, string fileName)
        {
            var fileType = System.IO.Path.GetExtension(fileName);
            var tempConverFilePath = AppDomain.CurrentDomain.BaseDirectory + "Files\\TempConverPdfFiles";
            if (!System.IO.Directory.Exists(tempConverFilePath))
            {
                Directory.CreateDirectory(tempConverFilePath);//创建文件夹
            }

            var convertName = Guid.NewGuid() + ".pdf";

            var splitArray = filePath.Split(new[] { "&" }, StringSplitOptions.RemoveEmptyEntries);
            var folder = HttpUtility.UrlDecode(splitArray[splitArray.Length - 2].Split('=')[1], System.Text.Encoding.UTF8).Replace("/", @"\");
            var subFolder = HttpUtility.UrlDecode(splitArray[splitArray.Length - 1].Split('=')[1], System.Text.Encoding.UTF8).Replace("/", @"\");
            var fileFullPath = AppDomain.CurrentDomain.BaseDirectory + "Files\\" + folder + "\\" + subFolder + "\\" + fileName;
            fileFullPath = HttpUtility.UrlDecode(fileFullPath, System.Text.Encoding.UTF8);

            if (fileType == ".doc" || fileType == ".docx")
            {
                Aspose.Words.Document docWord = new Aspose.Words.Document(fileFullPath);
                docWord.Save(tempConverFilePath + "\\" + convertName, Aspose.Words.SaveFormat.Pdf);
            }
            if (fileType == ".xlsx" || fileType == ".xls")
            {
                Aspose.Cells.Workbook excel = new Workbook(fileFullPath);
                excel.Save(tempConverFilePath + "\\" + convertName, Aspose.Cells.SaveFormat.Pdf);
            }
            //if (fileType == ".ppt" || fileType == ".pptx")
            //{
            //    Aspose.Slides.Presentation ppt = new Presentation(fileFullPath);
            //    ppt.Save(tempConverFilePath + "\\" + convertName, Aspose.Slides.Export.SaveFormat.Pdf);
            //}

            var convertPdfUrl = Request.Url.Scheme + "://" + Request.Url.Authority + "/Files/TempConverPdfFiles/" + convertName;

            dynamic jsonReturn = new ExpandoObject();
            jsonReturn = new { pdfUrl = convertPdfUrl };
            return new JsonResult { Data = jsonReturn };
        }
    }
}